package com.hsl.study.exercise.day0106;

import java.util.concurrent.*;

class Count {
    private static int total = 5000;

    public void sub() {
        for (int i = 1; i <= 3; i++) {
            String num = String.valueOf(i);
            while (true) {
                synchronized (Count.class) {
                    if (total > 0) {
                        System.out.print("售票员" + num + "卖出了第" + total + "张票,");
                        total--;
                        System.out.println("剩余" + total + "张票");

                    } else {
                        break;
                    }
                }
            }
        }
    }
}

public class TicketSelling {
    public static void main(String[] args) {
        Count count = new Count();
        // 创建一个线程池，核心线程数为3，最大线程数也为3
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                3,
                3,
                0,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        System.out.println("线程池已满，任务被拒绝");
                    }
                });

        // 提交三个售票任务
        for (int i = 0; i < 3; i++) {
            executor.submit(count::sub);
        }

 // 关闭线程池
        executor.shutdown();
    }
}
